package com.ruitu.router_module.support.widget;

import android.app.Dialog;
import android.content.Context;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.ruitu.arad.util.ToastUtils;
import com.ruitu.router_module.R;
import com.ruitu.router_module.bean.product.ProHome;
import com.ruitu.router_module.bean.product.Sku;
import com.ruitu.router_module.support.image.GImageLoader;
import com.ruitu.router_module.support.image.NumberUtils;
import com.wuhenzhizao.sku.bean.SkuAttribute;
import com.wuhenzhizao.sku.view.OnSkuListener;
import com.wuhenzhizao.sku.view.SkuSelectScrollView;
import com.wuhenzhizao.titlebar.utils.AppUtils;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.StyleRes;

public class ProductSkuDialog extends Dialog {
    //    private DialogProductSkuBinding binding;
    private View dialogView;
    private SkuSelectScrollView skuView;
    private ImageButton ib_sku_close;// 关闭
    private RelativeLayout rl_quantity;//数量
    private TextView btn_sku_quantity_minus, btn_sku_quantity_plus;// 数量减,数量加
    private EditText et_sku_quantity_input;// 输入数量
    private SimpleDraweeView iv_sku_logo;
    private TextView tv_sku_quantity, tv_sku_info;
    private Button btn_submit;
    private TextView tv_sku_selling_price, tv_sku_selling_price_unit;
    private View v_outside;// 上半部分

    private Context context;
    private ProHome product;
    private List<Sku> skuList;
    private Callback callback;

    private com.wuhenzhizao.sku.bean.Sku selectedSku;
    private String priceFormat;
    private String stockQuantityFormat;

    private boolean isCart;

    public ProductSkuDialog(@NonNull Context context) {
        this(context, R.style.CommonBottomDialogStyle);
    }

    public ProductSkuDialog(Context context, boolean cart) {
        this(context, R.style.CommonBottomDialogStyle, cart);
    }

    public ProductSkuDialog(@NonNull Context context, @StyleRes int themeResId) {
        this(context, themeResId, false);
    }

    public ProductSkuDialog(Context context, @StyleRes int themeResId, boolean cart) {
        super(context, themeResId);
        this.context = context;
        this.isCart = cart;
        initView();
    }


    private void initView() {
//        binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.dialog_product_sku, null, false);
//        setContentView(binding.getRoot());
        dialogView = View.inflate(context, R.layout.dialog_product_sku, null);
        setContentView(dialogView);
        skuView = dialogView.findViewById(R.id.scroll_sku_list);
        ib_sku_close = dialogView.findViewById(R.id.ib_sku_close);
        btn_sku_quantity_minus = dialogView.findViewById(R.id.btn_sku_quantity_minus);
        btn_sku_quantity_plus = dialogView.findViewById(R.id.btn_sku_quantity_plus);
        et_sku_quantity_input = dialogView.findViewById(R.id.et_sku_quantity_input);
        rl_quantity = dialogView.findViewById(R.id.rl_quantity);
        iv_sku_logo = dialogView.findViewById(R.id.iv_sku_logo);
        tv_sku_quantity = dialogView.findViewById(R.id.tv_sku_quantity);
        tv_sku_info = dialogView.findViewById(R.id.tv_sku_info);
        btn_submit = dialogView.findViewById(R.id.btn_submit);
        tv_sku_selling_price = dialogView.findViewById(R.id.tv_sku_selling_price);
        tv_sku_selling_price_unit = dialogView.findViewById(R.id.tv_sku_selling_price_unit);
        v_outside = dialogView.findViewById(R.id.v_outside);

        if (isCart) {
            rl_quantity.setVisibility(View.GONE);
        } else {
            rl_quantity.setVisibility(View.VISIBLE);
        }
        v_outside.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        ib_sku_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        btn_sku_quantity_minus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String quantity = et_sku_quantity_input.getText().toString();
                if (TextUtils.isEmpty(quantity)) {
                    return;
                }
                int quantityInt = Integer.parseInt(quantity);
                if (quantityInt > 1) {
                    String newQuantity = String.valueOf(quantityInt - 1);
                    et_sku_quantity_input.setText(newQuantity);
                    et_sku_quantity_input.setSelection(newQuantity.length());
                    updateQuantityOperator(quantityInt - 1);
                }
            }
        });
        btn_sku_quantity_plus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String quantity = et_sku_quantity_input.getText().toString();
                if (TextUtils.isEmpty(quantity) || selectedSku == null) {
                    return;
                }
                int quantityInt = Integer.parseInt(quantity);
                if (quantityInt < selectedSku.getStockQuantity()) {
                    String newQuantity = String.valueOf(quantityInt + 1);
                    et_sku_quantity_input.setText(newQuantity);
                    et_sku_quantity_input.setSelection(newQuantity.length());
                    updateQuantityOperator(quantityInt + 1);
                }
            }
        });
        et_sku_quantity_input.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId != EditorInfo.IME_ACTION_DONE || selectedSku == null) {
                    return false;
                }
                String quantity = et_sku_quantity_input.getText().toString();
                if (TextUtils.isEmpty(quantity)) {
                    return false;
                }
                int quantityInt = Integer.parseInt(quantity);
                if (quantityInt <= 1) {
                    et_sku_quantity_input.setText("1");
                    et_sku_quantity_input.setSelection(1);
                    updateQuantityOperator(1);
                } else if (quantityInt >= selectedSku.getStockQuantity()) {
                    String newQuantity = String.valueOf(selectedSku.getStockQuantity());
                    et_sku_quantity_input.setText(newQuantity);
                    et_sku_quantity_input.setSelection(newQuantity.length());
                    updateQuantityOperator(selectedSku.getStockQuantity());
                } else {
                    et_sku_quantity_input.setSelection(quantity.length());
                    updateQuantityOperator(quantityInt);
                }
                return false;
            }
        });
        // 选择监听
        skuView.setListener(new OnSkuListener() {
            @Override
            public void onUnselected(SkuAttribute unselectedAttribute) {
                selectedSku = null;
                GImageLoader.displayUrl(context, iv_sku_logo, product.getPic());
                tv_sku_quantity.setText(String.format(stockQuantityFormat, product.getStock()));
                String firstUnselectedAttributeName = skuView.getFirstUnelectedAttributeName();
                tv_sku_info.setText("请选择：" + firstUnselectedAttributeName);
                btn_submit.setEnabled(false);
                String quantity = et_sku_quantity_input.getText().toString();
                if (!TextUtils.isEmpty(quantity)) {
                    updateQuantityOperator(Integer.valueOf(quantity));
                } else {
                    updateQuantityOperator(0);
                }
                tv_sku_selling_price.setText(String.format(priceFormat, product.getPrice()));
            }

            @Override
            public void onSelect(SkuAttribute selectAttribute) {
                GImageLoader.displayUrl(context, iv_sku_logo, product.getPic());
                String firstUnselectedAttributeName = skuView.getFirstUnelectedAttributeName();
                tv_sku_info.setText("请选择：" + firstUnselectedAttributeName);
                tv_sku_selling_price.setText(String.format(priceFormat, product.getPrice()));
            }

            @Override
            public void onSkuSelected(com.wuhenzhizao.sku.bean.Sku sku) {
                selectedSku = sku;
                GImageLoader.displayUrl(context, iv_sku_logo, selectedSku.getMainImage());
                List<SkuAttribute> attributeList = selectedSku.getAttributes();
                StringBuilder builder = new StringBuilder();
                for (int i = 0; i < attributeList.size(); i++) {
                    if (i != 0) {
                        builder.append("　");
                    }
                    SkuAttribute attribute = attributeList.get(i);
                    builder.append("\"" + attribute.getValue() + "\"");
                }
                tv_sku_info.setText("已选：" + builder.toString());
                tv_sku_quantity.setText(String.format(stockQuantityFormat, selectedSku.getStockQuantity()));
                tv_sku_selling_price.setText(String.format(priceFormat, NumberUtils.formatNumber(selectedSku.getOriginPrice() / 100)));
                btn_submit.setEnabled(true);
                String quantity = et_sku_quantity_input.getText().toString();
                if (!TextUtils.isEmpty(quantity)) {
                    updateQuantityOperator(Integer.valueOf(quantity));
                } else {
                    updateQuantityOperator(0);
                }
            }
        });
        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String quantity = et_sku_quantity_input.getText().toString();
                if (TextUtils.isEmpty(quantity)) {
                    return;
                }
                int quantityInt = Integer.parseInt(quantity);
                if (quantityInt > 0 && quantityInt <= selectedSku.getStockQuantity()) {
                    callback.onAdded(selectedSku, quantityInt);
//                    dismiss();
                } else {
//                    Toast.makeText(getContext(), "商品数量超出库存，请修改数量", Toast.LENGTH_SHORT).show();
                    ToastUtils.showShortSafe("超出库存，请修改数量");
                }
            }
        });
    }

    public void setData(final ProHome product, final List<Sku> skuList, Callback callback) {
        this.product = product;

        List<com.wuhenzhizao.sku.bean.Sku> theirSkuList = new ArrayList<>();
        for (Sku sku : skuList) {
            com.wuhenzhizao.sku.bean.Sku theirSku = new com.wuhenzhizao.sku.bean.Sku();
            List<SkuAttribute> theirAttributeList = new ArrayList<>();
            for (Sku.Attribute attr : sku.getAttributes()) {
                SkuAttribute theirAttr = new SkuAttribute();
                String key = attr.getKey();
                if (TextUtils.isEmpty(key)) {
                    key = "数据有误";
                }
                theirAttr.setKey(key);
                String value = attr.getValue();
                if (TextUtils.isEmpty(value)) {
                    value = "数据有误";
                }
                theirAttr.setValue(value);
                theirAttributeList.add(theirAttr);
            }

            // 我们项目的sku封装到他们的sku
            theirSku.setAttributes(theirAttributeList);// 设置规格列表
            theirSku.setId(sku.getId());// 设置id
            theirSku.setMainImage(sku.getPic());
            long price = 0L;
            try {
                price = (long) (Double.parseDouble(sku.getPrice()) * 100);
            } catch (Exception e) {
                e.printStackTrace();
            }
            theirSku.setOriginPrice(price);// 原始价
            long proPrice = 0L;
            try {
                proPrice = (long) (Double.parseDouble(sku.getPromotionPrice()) * 100);
            } catch (Exception e) {
                e.printStackTrace();
            }
            theirSku.setSellingPrice(proPrice);// 促销价
            try {
                theirSku.setStockQuantity(Integer.parseInt(sku.getStock()));
            } catch (Exception e) {
                theirSku.setStockQuantity(0);
                e.printStackTrace();
            }
            theirSkuList.add(theirSku);// 添加到他们的sku列表
        }

        this.skuList = skuList;
        this.callback = callback;

        priceFormat = context.getString(R.string.comm_price_format);
        stockQuantityFormat = context.getString(R.string.product_detail_sku_stock);

        updateSkuData(theirSkuList);
        updateQuantityOperator(1);
    }

    private void updateSkuData(List<com.wuhenzhizao.sku.bean.Sku> theirSkuList) {
        skuView.setSkuList(theirSkuList);

        com.wuhenzhizao.sku.bean.Sku firstSku = theirSkuList.get(0);
        if (firstSku.getStockQuantity() > 0) {
            selectedSku = firstSku;
            // 选中第一个sku
            skuView.setSelectedSku(selectedSku);

            GImageLoader.displayUrl(context, iv_sku_logo, selectedSku.getMainImage());
            tv_sku_selling_price.setText(String.format(priceFormat, NumberUtils.formatNumber(selectedSku.getOriginPrice() / 100)));
            tv_sku_selling_price_unit.setText("/" + product.getUnit());
            tv_sku_quantity.setText(String.format(stockQuantityFormat, selectedSku.getStockQuantity()));
            btn_submit.setEnabled(selectedSku.getStockQuantity() > 0);
            List<SkuAttribute> attributeList = selectedSku.getAttributes();
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < attributeList.size(); i++) {
                if (i != 0) {
                    builder.append("　");
                }
                SkuAttribute attribute = attributeList.get(i);
                builder.append("\"" + attribute.getValue() + "\"");
            }
            tv_sku_info.setText("已选：" + builder.toString());
        } else {
            GImageLoader.displayUrl(context, iv_sku_logo, product.getPic());
            tv_sku_selling_price.setText(String.format(priceFormat, product.getPrice()));
            tv_sku_selling_price_unit.setText("/" + product.getUnit());
            tv_sku_quantity.setText(String.format(stockQuantityFormat, product.getStock()));
            btn_submit.setEnabled(false);
            tv_sku_info.setText("请选择：" + skuList.get(0).getAttributes().get(0).getKey());
        }
    }

    private void updateQuantityOperator(int newQuantity) {
        if (selectedSku == null) {
            btn_sku_quantity_minus.setEnabled(false);
            btn_sku_quantity_plus.setEnabled(false);
            et_sku_quantity_input.setEnabled(false);
        } else {
            if (newQuantity <= 1) {
                btn_sku_quantity_minus.setEnabled(false);
                btn_sku_quantity_plus.setEnabled(true);
            } else if (newQuantity >= selectedSku.getStockQuantity()) {
                btn_sku_quantity_minus.setEnabled(true);
                btn_sku_quantity_plus.setEnabled(false);
            } else {
                btn_sku_quantity_minus.setEnabled(true);
                btn_sku_quantity_plus.setEnabled(true);
            }
            et_sku_quantity_input.setEnabled(true);
        }
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        // 解决键盘遮挡输入框问题
        Window window = getWindow();
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        window.setGravity(Gravity.BOTTOM);
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        window.getDecorView().setPadding(0, 0, 0, 0);
        // KeyboardConflictCompat.assistWindow(getWindow());
        AppUtils.transparencyBar(getWindow());
    }


    public interface Callback {
        void onAdded(com.wuhenzhizao.sku.bean.Sku sku, int quantity);
    }
}
